/**
 * Created by gitbong on 14-3-7.
 * base on jq1.6.2 gbbase gbmvc
 */
var gb = gb = gb || {};
(function (gb) {

    var htmlMap = {};
    var imgLoadedMap = {};
    var defaultPanel = '';

    gb.site = {};
    gb.site.Site = gb.mvc.V.extend({
        config: '',

        _classMap: '',
        _htmlMap: '',

        ctor: function (domId_, config_) {
            this._super(domId_, $('#' + domId_));

            var self = this;

            this.config = config_;
            this._classMap = {};
            this._htmlMap = {};

            defaultPanel = this.config.defaultPanel;

            console.log(defaultPanel);

            gb.mvc.registerV(this);

            this.view.append("<layer class='BACKGROUND'></layer>");
            this.view.append("<layer class='SCENE'></layer>");
            this.view.append("<layer class='TOP'></layer>");
            this.view.append("<layer class='POPUP'></layer>");
            this.view.append("<layer class='LOADING'></layer>");

            for (var i in this.config.panels) {
                var p = this.config.panels;
                var c = p[i];
//                console.log(c, i)
                if (c.loading == '' || c.loading == null) {
                    delete c.loading;
                } else {
                    if (p[c.loading] == null) {
                        worr("（>_<）!  \n\nDo not have loading named: \" " + c.loading + "\" ! ");
                    } else {
                        delete p[c.loading].loading;
                    }
                }

                $.ajax({
                    url: c.html,
                    dataType: 'html',
                    type: 'GET',
                    mydata: {panelName: i},
                    success: function (data) {
                        var panelName = this.mydata.panelName;
                        htmlMap[panelName] = data;
//                        console.log(data, "--", panelName);
//                        console.log(htmlMap)
                    }
                });
            }
        },
        handleNote: function (note_) {
            switch (note_.name) {
            }
        },
        registerPanel: function (name_, class_) {
            this._classMap[name_] = class_;
        },
        addPanel: function (name_, data_, layer_) {
            if (hasExist(name_)) {
                worr("（>_<）!  \n\nThe panel named: \"" + name_ + "\"  has exist !");
                return;
            }

            if (layer_ == gb.site.Layer.SCENE) {
                location.hash = name_;
            }

            var lp = new LoadProgress(this.config, this._classMap);
            lp.start(name_, data_, layer_);
        },
        showDefaultPanel: function (data_) {
            var self = this;
            var hash = location.hash == "" ? "" : location.hash.split('#')[1];
            var panel;
            if (hash == '' || (hash == defaultPanel || this.config.panels[hash] == null)) {
                location.hash = '';
                panel = defaultPanel;
            } else {
                location.hash = hash;
                panel = hash;
            }
            this.addPanel(panel, data_, gb.site.Layer.SCENE);
            $(window).unbind().bind('hashchange', function () {
//                self.showDefaultPanel()
            })
        },
        removePanel: function (name_, data_) {
            var v = gb.mvc.getV(name_);
            if (v)
                v.askToRemove(data_);
        },
        getPanel: function (name_) {
            return gb.mvc.getV(name_);
        },
        preloadPanel: function (panel_, completeFn_) {
            var imgs = this.config.panels[panel_].imgs;
            if (imgs != null) {
                if (imgs.length > 0) {
                    var loader = new gb.net.ImgsLoader(imgs);
                    if (completeFn_ != null)
                        loader.sgComplete.add(completeFn_);
                    loader.load();
                } else {

                }
            } else {

            }
        }
    });

    var LoadProgress = gb.classes.Class.extend({
        _panel: null,
        _data: null,
        _layer: null,

        _classMap: null,
        _config: null,
        _loader: null,

        _loadingIns: null,
        _$loading: null,
        _panelHtml: null,

        ctor: function (config_, classMap_) {
            this._classMap = classMap_;
            this._config = config_;
            this._loader = new HtmlLoader(config_);
            this._loader.sgProgress.add(this._onPro, this);
            this._loader.sgLoaded.add(this._onLoaded, this);
        },
        start: function (panel_, data_, layer_) {
            this._panel = panel_;
            this._data = data_;
            this._layer = layer_;
            this._loadHtml(this._panel);
        },
        _loadHtml: function (panel_) {
            if (this._haveLoading(panel_)) {
//                console.log(0, panel_);
                //load loading first
                if (imgLoadedMap[panel_] == 'loaded') {
                    this._loader.loadHtml(panel_);
                } else {
//                    console.log(1, panel_);
                    this._loadHtml(this.getPanelConfig(panel_).loading);
                }
            } else {
                //load html
//                console.log(2, panel_)
                this._loader.loadHtml(panel_);
            }
        },
        _onPro: function (pro_) {
            if (this._loadingIns != null) {
                this._loadingIns.onProgress(pro_.progress);
            }
        },
        _onLoaded: function (data_) {
            var pName = data_.panelName;
            //loading loaded
            if (this.getPanelConfig(this._panel).loading == pName) {
                if (this._classMap[pName] == null)
                    this._classMap[pName] = gb.site.Loading;
                var lv = this._creatJQView(data_.panelName, data_.html, gb.site.Layer.LOADING); //loading view
                var ins = this._creatIns(pName, lv);
                ins._sgLoadScene.add(this._onLoadPanel, this);
                ins._sgShowScene.add(this._onShowPanel, this);
                gb.mvc.registerV(ins);
//                return;
                ins.askToAdd();
                this._loadingIns = ins;
                this._$loading = lv;
            }
            //panel loaded
            else {
                this._panelHtml = data_.html;
                if (this._loadingIns != null) {
                    this._loadingIns.onComplete();
                } else {
                    var v = this._creatJQView(data_.panelName, this._panelHtml, this._layer);
                    if (this._classMap[data_.panelName] == null)
                        this._classMap[data_.panelName] = gb.site.Panel;
                    var ins = this._creatIns(data_.panelName, v);
                    gb.mvc.registerV(ins);
//          console.log(this._data);
                    ins.askToAdd(this._data);
                }
//        console.log('#panel loaded', this._loadingIns != null, this, data_);
            }
        },
        _onLoadPanel: function (ins_) {
            ins_._sgLoadScene.remove(this._onLoadPanel);
            this._loader.loadHtml(this._panel);
        },
        _onShowPanel: function (ins_) {
            ins_._sgShowScene.remove(this._onShowPanel);
            var v = this._creatJQView(this._panel, this._panelHtml, this._layer);
//      console.log('on show panel:', this._layer);
            if (this._classMap[this._panel] == null)
                this._classMap[this._panel] = gb.site.Panel;
            var ins = this._creatIns(this._panel, v);
            gb.mvc.registerV(ins);
            ins.askToAdd(this._data);
        },
        _creatJQView: function (panel_, html_, layer_) {
            var dom = "<div id='panel_" + panel_ + "' class='gb_panel'></div>";
            $('.' + layer_).before(dom);
            $('#panel_' + panel_).html(html_).css('display', 'none');
            return $('#panel_' + panel_);
        },
        _creatIns: function (panel_, view_) {
            var ins = new this._classMap[panel_](panel_, view_);
            return ins;
        },
        _haveLoading: function (panel_) {
            var cg = this.getPanelConfig(panel_);
            return !(cg.loading == "" || cg.loading == null);
        },
        getPanelConfig: function (panel_) {
            return this._config.panels[panel_];
        }
    });

    var HtmlLoader = gb.classes.Class.extend({
        //load var
        _config: null,
        _htmlMap: null,

        sgProgress: null,
        sgLoaded: null,

        ctor: function (data_) {
            this._config = data_;
            this._htmlMap = {};
            this.sgProgress = new gb.classes.Signal;
            this.sgLoaded = new gb.classes.Signal;
        },
        loadHtml: function (panelName_) {
//            console.log(3, panelName_);
//            console.log(htmlMap[panelName_] != null)
            var self = this;

            if (htmlMap[panelName_] != null) {

                var $imgArr = self.getPanelConfig(panelName_).imgs;

                if ($imgArr.length > 0) {
                    if (imgLoadedMap[panelName_] == 'loaded') {
                        console.log('loaded:', panelName_);
                        self.sgLoaded.dispatch({panelName: panelName_, html: htmlMap[panelName_]});
                    } else {
                        self._loadImages(panelName_, htmlMap[panelName_], $imgArr);
                    }
                } else {
                    self.sgProgress.dispatch({panelName: panelName_, progress: 0});
                    self.sgProgress.dispatch({panelName: panelName_, progress: 1});
                    setTimeout(function () {
                        self.sgLoaded.dispatch({panelName: panelName_, html: htmlMap[panelName_]});
                    }, .0000001);
                }
                return;
            }
            var $panelConfig = this.getPanelConfig(panelName_);
            $.ajax({
                url: $panelConfig.html,
                dataType: 'html',
                type: 'GET',
                mydata: {self: this, panelName: panelName_},
                success: this._onHtmlLoaded
            });
        },
        //step1
        _onHtmlLoaded: function (data_) {
            var self = this.mydata.self;
            var $panelName = this.mydata.panelName;
            self._htmlMap[$panelName] = data_;
            var $imgArr = self.getPanelConfig($panelName).imgs;
            if ($imgArr.length > 0) {
                self._loadImages($panelName, data_, $imgArr);
            } else {
                self.sgProgress.dispatch({panelName: $panelName, progress: 1});
                self.sgLoaded.dispatch({panelName: $panelName, html: self._htmlMap[$panelName]});
            }
        },
        //step2
        _loadImages: function (panelName_, html_, imgArr_) {
            var loader = new gb.net.ImgsLoader(imgArr_);
            loader.panel = panelName_;
            loader.html = html_;
            loader.sgProgress.add(this._onImgPro, this);
            loader.sgComplete.add(this._onImgLoadComplete, this);
            loader.load();
        },
        _onImgPro: function (e) {
            var $panelName = e.target.panel;
            var $pro = e.target.progress;
            this.sgProgress.dispatch({panelName: $panelName, progress: $pro});
        },
        _onImgLoadComplete: function (e) {
            e.target.sgProgress.remove(this._onImgPro);
            e.target.sgComplete.remove(this._onImgLoadComplete);

            var $panelName = e.target.panel;
            var $html = e.target.html;

            imgLoadedMap[$panelName] = 'loaded';

            this.sgLoaded.dispatch({panelName: $panelName, html: $html});
        },
        getPanelConfig: function (panelName_) {
            return this._config.panels[panelName_];
        }
    });

    //===================

    gb.site.Panel = gb.mvc.V.extend({
        loadingView: null,

        ctor: function (name_, view_) {
            gb.window.sgResize.add(this.onResize, this);
            this._super(name_, view_);
        },
        askToAdd: function (data_) {
            this.toAdd();
        },
        toAdd: function () {
            this.view.css('display', 'block');
//      this._sgReadyToAdd.dispatch(this);
        },
        askToRemove: function (data_) {
            this.toRemove();
        },
        toRemove: function () {
//      this._sgReadyToRemove.dispatch(this);
            gb.mvc.removeV(this.name);
            this.view.remove();
        },
        destroy: function () {
            this.noteList = [];
        },
        onResize: function (w_, h_) {
        }
    });
    gb.site.Loading = gb.site.Panel.extend({
        _panel: -1,
        _sgLoadScene: null,
        _sgShowScene: null,
        ctor: function (name_, view_) {
            this._super(name_, view_);
            this._sgLoadScene = new gb.classes.Signal;
            this._sgShowScene = new gb.classes.Signal;
        },
        toAdd: function () {
            this.loadPanel();
            this.view.css('display', 'block');
        },
        toRemove: function () {
            gb.mvc.removeV(this.name);
            this.view.remove();
        },
        onProgress: function (pro_) {

        },
        onComplete: function () {
            this.showPanel();
            this.closeLoading();
        },
        loadPanel: function () {
            this._sgLoadScene.dispatch(this);
        },
        showPanel: function () {
            this._sgShowScene.dispatch(this);
        },
        closeLoading: function () {
            this.askToRemove();
        }
    });

    //========

    function hasExist(panel_) {
        return $('#panel_' + panel_).length > 0;
    }

    function worr(msg_) {
        alert(msg_);
    }

    var _events = {
        SHOW_PANEL: 'SHOW_PANEL',
        CLOSE_LOADING: 'CLOSE_LOADING'
    };

    gb.site.Layer = {
        BACKGROUND: 'BACKGROUND',
        SCENE: 'SCENE',
        TOP: 'TOP',
        LOADING: 'LOADING',
        POPUP: 'POPUP'
    };
    gb.site.Event = {
        HTML_PROGRESS: 'HTML_PROGRESS',
        HTML_LOADED: 'HTML_LOADED'
    };
    gb.site = gb.site;
})(gb);

//var config = {
//  panels: {
//    loading: {
//      html: 'htmls/loading.html',
//      imgs: ['imgs/1.jpg'],
//      loading: 'loading'
//    },
//    nav: {
//      html: 'htmls/nav.html',
//      imgs: ['imgs/1.jpg', 'imgs/2.jpg'],
//      loading: 'loading'
//    },
//    panel0: {
//      html: 'htmls/panel0.html',
//      imgs: ['imgs/1.jpg', 'imgs/2.jpg'],
//      loading: 'loading'
//    },
//    panel1: {
//      html: 'htmls/panel1.html',
//      imgs: ['imgs/1.jpg', 'imgs/2.jpg']
////      loading: 'loading'
//    },
//    panel2: {
//      html: 'htmls/panel2.html',
//      imgs: ['imgs/1.jpg', 'imgs/2.jpg'],
//      loading: 'loading'
//    }
//  }
//};